﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using HeyoUi;
using HeyoUi.Models.Data.BMCLAPI;
using HeyoUi.Models.Data.Game;
using HeyoUi.Util;
using KMCCC.Tools;
using Newtonsoft.Json;

namespace Heyo.Launcher.Util
{
    internal class ForgeInstaller
    {
        /// <summary>
        /// 安装Forge
        /// </summary>
        /// <param name="forgePath">forge安装文件的完整路径</param>
        /// <param name="newGameName">新配置文件的名字，为null则根据forge版本自动决定</param>
        /// <returns>是否成功，以及新配置文件的名字</returns>
        internal static (bool,string) Install(string forgePath,string newGameName=null)
        {
            string tmpPath = Path.GetDirectoryName(forgePath) + "\\tmp\\";
            if (!ZipTools.Unzip(forgePath, tmpPath, new UnzipOptions()))
                return (false,null);

            FileStream installProfileStream = File.Open(Path.Combine(tmpPath, "install_profile.json"),FileMode.Open);
            StreamReader reader=new StreamReader(installProfileStream);
            InstallProfileJson installProfileJson =
                JsonConvert.DeserializeObject<InstallProfileJson>(reader.ReadToEnd());

            reader.Dispose();
            installProfileStream.Close();

            if (installProfileJson == null)
                return (false,null);
            InstallJson installJson = installProfileJson.Install;
            McGameJson jsonInfo = installProfileJson.VersionInfo;
            
            if (installJson == null || jsonInfo == null) return (false,null);
            JsonSerializerSettings jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            if (!string.IsNullOrWhiteSpace(newGameName))
                jsonInfo.Id = newGameName;
            string versionJsonStr = JsonConvert.SerializeObject(jsonInfo, Formatting.Indented, jSetting);

            string mcVersion = installJson.Minecraft;
            string installedName = string.IsNullOrWhiteSpace(newGameName) ? installJson.Target : newGameName;
            //版本低于1.13.2
            if (string.Compare(mcVersion, "1.13.2", StringComparison.Ordinal)<0)
            {
                string filePath = installJson.FilePath;
                if (filePath == null) return (false,null);
                string path= GameLocator.GetLibPath(installJson.Path);
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                if(File.Exists(path))
                    File.Delete(path);
                File.Move(Path.Combine(tmpPath,filePath),path);

                string jsonPath =
                    GameLocator.GetJsonPath(installedName);
                
                if (!Directory.Exists(Path.GetDirectoryName(jsonPath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(jsonPath));

                FileStream mcJsonFile = File.Open(jsonPath, FileMode.Create);
                StreamWriter writer=new StreamWriter(mcJsonFile);
                writer.Write(versionJsonStr);
                writer.Dispose();
                mcJsonFile.Close();
            }
            else
            {

            }
            
            Directory.Delete(tmpPath,true);
            return (true, installedName);
        }

        private class InstallProfileJson
        {
            [JsonProperty("install")]
            public InstallJson Install { get; set; }
            [JsonProperty("versionInfo")]
            public McGameJson VersionInfo { get; set; }
        }
        private class InstallJson
        {
            [JsonProperty("target")]
            public string Target { get; set; }
            [JsonProperty("version")]
            public string Version { get; set; }
            [JsonProperty("path")]
            public string Path { get; set; }
            [JsonProperty("filePath")]
            public string FilePath { get; set; }
            [JsonProperty("minecraft")]
            public string Minecraft { get; set; }
        }
    }
}
